package cn.kailangtu.dataspot;

import org.apache.commons.net.ntp.NTPUDPClient;
import org.apache.commons.net.ntp.TimeInfo;

import java.net.InetAddress;
import java.util.Date;

public class NtpClientWithLib {
    private static final String NTP_SERVER = "ntp.aliyun.com";
    private static final int TIMEOUT_MS = 10_000;

    public static Date getNtpTime() throws Exception {

        NTPUDPClient client = new NTPUDPClient();

        client.setDefaultTimeout(TIMEOUT_MS);

        client.open();

        //InetAddress hostAddr = InetAddress.getByName(NTP_SERVER);
        InetAddress hostAddr = InetAddress.getByName("10.71.252.62");

        TimeInfo timeInfo = client.getTime(hostAddr);

        timeInfo.computeDetails(); // 计算偏移和延迟
        long ntpTime = timeInfo.getReturnTime(); // 获取时间（毫秒）
        client.close();
        return new Date(ntpTime);
    }

    public static void main(String[] args) throws Exception {
        Date ntpTime = getNtpTime();
        System.out.println("NTP 时间: " + ntpTime);
    }
}